<?php

// 对于计算密集型任务，需要将其分发给多个消费者进行处理。


require_once dirname(__DIR__) . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection(
	'49.232.138.70',
    5672,
    'finley',         //user
    'sfdwqdwq3crEt'   //password
);

$channel = $connection->channel();

$channel->queue_declare('task_queue', false, true, false, false);

echo " [*] Waiting for messages. To exit press CTRL+C\n";

$callback = function ($msg) {
    echo ' [x] Received ', $msg->body, "\n";
    sleep(substr_count($msg->body, '.'));
    echo " [x] Done\n";
    $msg->ack();
};


// 不要给一个worker多个消息
// 在worker处理并确认前一条消息之前，不要向它发送新消息。相反，它将把它分派给下一个不太忙的工人。
$channel->basic_qos(null, 1, null);

$channel->basic_consume('task_queue', '', false, false, false, false, $callback);

while ($channel->is_consuming()) {
    $channel->wait();
}

$channel->close();
$connection->close();